package com.iqiyi.pps.epg.core.dao.record;

import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.record.*;
import com.iqiyi.pps.epg.core.dao.base.BaseDao;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.model.record.RecordTask;
import com.iqiyi.pps.epg.core.utils.DateTimeUtil;
import com.iqiyi.pps.epg.core.utils.SqlUtil;
import com.iqiyi.pps.epg.core.utils.TransUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.type.StringType;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by karkarrotxu on 2018/4/11.
 */
@Component
public class RecordTaskDao extends BaseDao<RecordTask> {
    public static final String HQL_DELETE_TASK_BEFORE = "update RecordTask set status = 0 where status = 1 and planId =? and taskStopTime > ?";

    public TRecordTaskDataPage findTaskPage(TPage page, TFilter filter) {
        List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
        Page<RecordTask> dbPage = TransUtil.buildPage(page);
        Page<RecordTask> pageData = findPage(dbPage, filterList);
        List<RecordTask> dataList = pageData.getResult();
        TRecordTaskDataPage dataPage = new TRecordTaskDataPage();
        page.setTotalCount(pageData.getTotalCount());
        dataPage.setTPage(page);
        List<TRecordTaskData> tList = transToTRecordTaskList(dataList);
        dataPage.setResult(tList);
        return dataPage;
    }

    private List<TRecordTaskData> transToTRecordTaskList(List<RecordTask> dataList) {
        List<TRecordTaskData> resultList = new ArrayList<>();
        TRecordTaskData tPlan = null;
        for (RecordTask tempData : dataList) {
            tPlan = transToTRecordTaskData(tempData);
            resultList.add(tPlan);
        }
        return resultList;
    }

    public TRecordTaskData transToTRecordTaskData(RecordTask tempData) {
        TRecordTaskData _tEntity = new TRecordTaskData();
        if (tempData == null) {
            return _tEntity;
        }
        _tEntity.setId(tempData.getId());
        _tEntity.setStatus(tempData.getStatus());
        return _tEntity;
    }

    public TRecordTaskLibraryPage findTaskLibraryPage(TPage page, TFilter filter) {
        String tempPattern = "${PARAMS}";
        String resultPattern = " record_task.id,record_task.plan_id, " +
                " col.id,col.col_name, channel.id,channel.channel_name," +
                " col.category_id,col.has_auth,record_task.task_status ," +
                "    record_task.task_start_time,record_task.task_stop_time,record_task.create_time ";
        String totalPattern = "COUNT(*) as total";
        List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
        String hql = "select " + tempPattern + " from record_task , record_plan , record_channel channel,record_col col where record_task.plan_id = record_plan.id and record_plan.channel_id = channel.id and record_plan.col_id = col.id";
        String original = page.getOrderBy();
        page.setOrderBy(rebuildOrderBy(original, "record_task"));
        Page<TRecordPlanLibrary> dbPage = TransUtil.buildPage(page);
        String sql = SqlUtil.buildWithPropertyFilter(hql, filterList);
        boolean skipQuery = false;
        if (dbPage.isAutoCount()) {
            logger.debug("[build sql totalPattern]" + sql.replace(tempPattern, totalPattern));
            String totalCount = getSession().createSQLQuery(sql.replace(tempPattern, totalPattern))
                    .addScalar("total", new StringType()).list().get(0).toString();

            page.setTotalCount(Long.valueOf(totalCount));
            if (page.getTotalCount() == 0) {
                skipQuery = true;
                logger.debug("[skip query  case total is zero ]");
            }
        }
        List<TRecordTaskLibrary> dataList = new ArrayList<>();
        if (!skipQuery) {
            sql = SqlUtil.buildAppendPage(dbPage, sql);
            sql = SqlUtil.buildAppendPageLimit(dbPage, sql);
            logger.debug("[build sql resultPattern ]" + sql.replace(tempPattern, resultPattern));
            List result = getSession().createSQLQuery(sql.replace(tempPattern, resultPattern)).list();
            TRecordTaskLibrary singleData = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Object single : result) {
                Object[] obj = (Object[]) single;
                singleData = new TRecordTaskLibrary();
                singleData.setId(Long.valueOf("" + obj[0]));
                singleData.setPlanId(Long.valueOf("" + obj[1]));
                singleData.setColId(Long.valueOf("" + obj[2]));
                singleData.setColName("" + obj[3]);
                singleData.setChannelId(Long.valueOf("" + obj[4]));
                singleData.setChannelName("" + obj[5]);
                singleData.setCategoryId(Integer.valueOf("" + obj[6]));
                singleData.setHasAuth(Integer.valueOf("" + obj[7]));
                singleData.setTaskStatus(Integer.valueOf("" + obj[8]));
                singleData.setTaskStartTime(obj[9] + "");
                singleData.setTaskStopTime(obj[10] + "");
                singleData.setCreateTime(sdf.format(obj[11]));
                dataList.add(singleData);
            }
        }
        TRecordTaskLibraryPage libraryPage = new TRecordTaskLibraryPage();
        page.setOrderBy(original);
        libraryPage.setTPage(page);
        libraryPage.setResult(dataList);
        return libraryPage;
    }

    private String rebuildOrderBy(String original, String aliasName) {
        String[] params = original.split(",");
        StringBuilder sBuilder = new StringBuilder();
        for (String param : params) {
            sBuilder.append(aliasName + "." + param);
            sBuilder.append(",");
        }
        if (sBuilder.length() > 0) {
            sBuilder.deleteCharAt(sBuilder.length() - 1);
        }
        return sBuilder.toString();
    }

    public void batchSave(List<RecordTask> list) {
        Session session = getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        try {
            for (RecordTask temp : list) {
                session.save(temp);
            }
            transaction.commit();
        } catch (Exception e) {
            logger.error(e.getMessage());
            transaction.rollback();
        } finally {
            session.close();
        }
    }

    public void batchUpdate(List<RecordTask> list) {
        Session session = getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        try {
            for (RecordTask temp : list) {
                session.update(temp);
            }
            transaction.commit();
        } catch (Exception e) {
            logger.error(e.getMessage());
            transaction.rollback();
        } finally {
            session.close();
        }
    }

    public void doClearTaskBefore(long planId, long newStartTime) {
       int exeNum =  createQuery(HQL_DELETE_TASK_BEFORE).setLong(0,planId).setString(1,DateTimeUtil.transLongFormat(newStartTime)).executeUpdate();
       logger.info("[doClearTaskBefore][planId={},time={},num={}]",planId,DateTimeUtil.transLongFormat(newStartTime),exeNum);
    }
}
